import React, { Component } from 'react';
import Head from './Head';
import './bought.css';
import { get } from '../../../Lib/Http';
import apiUrl from '../../../Config/web';
import { Spin } from 'antd';
import { BrowserRouter as Router, Route, Link, Switch} from 'react-router-dom';

class Bought extends Component {

    constructor(props){
        super(props);

        this.state = {
            'wrapper_height':'',
            'data':''
        }

    }

    componentDidMount(){

        let that = this;

        let _b_url = that.props.history.location.pathname;
        window._hmt.push(['_trackPageview', _b_url]);

        get(apiUrl.bought, {}, function(info){

            let height = window.innerHeight - 44 - 15;

            if(info.data.code !== 0){
                return;
            }

            that.setState({
                'wrapper_height':height,
                'data':info.data.data
            });

        }, function(error){

            console.log(error);

        });
    }

    renderBook(data){

        let start = 0;
        let key = 0;
        let bookArray = [];
        bookArray[key] = [];

        data.map((value, index)=>{
            bookArray[key].push(value);
            start++;
            if(start>=3){
                start = 0;
                key++;
                bookArray[key] = [];
            }
        });

        return bookArray.map((value, index)=>{
            return (
                <div key={index} className="bought-book-row">
                    {
                        value.map((bookData, bookIndex)=>{
                            let src = '/detail/'+bookData.book_id
                            return(
                                <Link key={bookIndex} to={src}>
                                    <div className="bought-book-box">
                                        <img className="bought-book-box-img" src={bookData.book_img} />
                                        <div className="bought-book-name">{bookData.book_name}</div>
                                    </div>
                                </Link>
                            )
                        })
                    }
                </div>
            )
        })
                        
    }

    render() {

        if(this.state.data === ''){
            return (<Spin tip="Loading..." className="home-loding" size="large" />);
        };

        let data = this.state.data;

        return (
            <div className="root">
                <Head url='/user' history={this.props.history} title='已购买试卷' />
                <div style={{'height':this.state.wrapper_height}} className="bought-content-wrapper">
                    {
                        this.renderBook(data)
                    }
                </div>
            </div>
        );
    }
}

export default Bought;